package com.hrabun.goodmorningalarm;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class RadioStationDAO {

	Context context;
	DBHelper dbHelper;
	SQLiteDatabase db;
	
	public RadioStationDAO(Context ctx) {
		this.context = ctx;
		dbHelper = new DBHelper(context);
		db = dbHelper.getWritableDatabase();
	}
	
	public RadioStation getStationByName(String name) {
		RadioStation rStation = new RadioStation();
		Cursor c = db.query(Global.DB_TABLE_STATIONS_NAME, 
				null, 
				Global.DB_COLUMN_RADIO_STATION_NAME+" = "+name, 
				null, 
				null, 
				null, 
				null);
		if (c.moveToFirst()) {
			rStation.setStationID(c.getString(Global.DB_RADIO_STATION_ID_INDEX));
			rStation.setStationName(c.getString(Global.DB_RADIO_STATION_NAME_INDEX));
			rStation.setStationURL(c.getString(Global.DB_RADIO_STATION_URL_INDEX));
		} while (c.moveToNext());
		c.close();
		db.close();
		return rStation;
	}
	
	public RadioStation getStationByID(String id) {
		RadioStation rStation = new RadioStation();
		Cursor c = db.query(Global.DB_TABLE_STATIONS_NAME, 
				null, 
				Global.DB_COLUMN_RADIO_STATION_ID+" = "+id, 
				null, 
				null, 
				null, 
				null);
		if (c.moveToFirst()) {
			rStation.setStationID(c.getString(Global.DB_RADIO_STATION_ID_INDEX));
			rStation.setStationName(c.getString(Global.DB_RADIO_STATION_NAME_INDEX));
			rStation.setStationURL(c.getString(Global.DB_RADIO_STATION_URL_INDEX));
		} while (c.moveToNext());
		c.close();
		db.close();
		return rStation;
	}
	
	public RadioStation getStationByUrl(String url) {
		RadioStation rStation = new RadioStation();
		Cursor c = db.query(Global.DB_TABLE_STATIONS_NAME, 
				null, 
				Global.DB_COLUMN_RADIO_STATION_URL+" = "+url, 
				null, 
				null, 
				null, 
				null);
		if (c.moveToFirst()) {
			rStation.setStationID(c.getString(Global.DB_RADIO_STATION_ID_INDEX));
			rStation.setStationName(c.getString(Global.DB_RADIO_STATION_NAME_INDEX));
			rStation.setStationURL(c.getString(Global.DB_RADIO_STATION_URL_INDEX));
		} while (c.moveToNext());
		c.close();
		db.close();
		return rStation;
	}
	
	public ArrayList<RadioStation> getAllRadioStations() {
		RadioStation rStation;
		ArrayList<RadioStation> stations = new ArrayList<RadioStation>();
		Cursor c = db.query(Global.DB_TABLE_STATIONS_NAME, 
				null, 
				null, 
				null, 
				null, 
				null, 
				null);
		if (c.moveToFirst()) {
			do {
				rStation = new RadioStation();
				rStation.setStationID(c.getString(Global.DB_RADIO_STATION_ID_INDEX));
				rStation.setStationName(c.getString(Global.DB_RADIO_STATION_NAME_INDEX));
				rStation.setStationURL(c.getString(Global.DB_RADIO_STATION_URL_INDEX));
				stations.add(rStation);
			} while (c.moveToNext());
		}
		c.close();
		db.close();
		return stations;
	}
}
